假如有個類別Employee
, 用來處理支付薪水的函數Pay()
public class Employee
{
public void Pay()
{
Money amount = new Money();
foreach(var card in timeCards)
{
if(payPeriod.Contains(date))
{
amount.Add(card.Hours * payRate);
}
}
payDispatcher.Pay(this, date, amount);
}
}
需要多一個功能, 用來記錄支付薪資後的log
public class Employee
{
private void DispatchPayment()
{
Money amount = new Money();
foreach(var card in timeCards)
{
if(payPeriod.Contains(date))
{
amount.Add(card.Hours * payRate);
}
}
payDispatcher.Pay(this, date, amount);
}
public void Pay()
{
LogPayment();
DispatchPayment();
}
private void LogPayment()
{
//...
}
}
上述這種改法, 外部人不影響仍是呼叫Pay()
函數, 但內部實作已改變.
與前面的Employee
範例一樣:
public class Employee
{
public void Pay()
{
Money amount = new Money();
foreach(var card in timeCards)
{
if(payPeriod.Contains(date))
{
amount.Add(card.Hours * payRate);
}
}
payDispatcher.Pay(this, date, amount);
}
}
採用裝飾者模式, 繼承Employee
類別並實作log功能
public class LoggingEmployee : Employee
{
public LoggingEmployee(Employee e)
{
employee = e;
}
public void Pay()
{
LogPayment();
employee.Pay();
}
private void LogPayment()
{
//...
}
}